left-fold, reduce

Chat GPT 4o answer

✅ left-fold란?

left-fold는 보통 foldl 또는 reduce라고 불리는 연산으로, 다음과 같은 방식으로 동작합니다:

foldl(f, initialValue, [a1, a2, a3, ..., an])

이것은 다음처럼 평가됩니다:

f(f(f(f(initialValue, a1), a2), a3), ..., an)

즉, 리스트의 왼쪽부터 오른쪽으로 차례대로 값을 누적해서 결과를 만드는 방식입니다.


📦 예제 (TypeScript 기준)

const events = [1, 2, 3, 4];

const sum = events.reduce((acc, curr) => acc + curr, 0);
// sum === 10

🔁 이벤트 소싱과의 연결: 프로젝션

이벤트 소싱에서 프로젝션은 이렇게 정의됩니다:

과거 이벤트들의 리스트를 왼쪽부터 오른쪽으로 적용하여 현재 상태를 계산하는 과정

이건 본질적으로 left-fold입니다!

예를 들어 사용자 계좌(Account)의 상태를 만들기 위해 다음 이벤트가 있다고 해봅시다:

[
  { type: "Opened", balance: 0 },
  { type: "Deposited", amount: 100 },
  { type: "Withdrawn", amount: 40 }
]

이를 left-fold로 계산하면:

const events = [
  { type: "Opened", balance: 0 },
  { type: "Deposited", amount: 100 },
  { type: "Withdrawn", amount: 40 }
];

const accountProjection = events.reduce((state, event) => {
  switch (event.type) {
    case "Opened":
      return { balance: event.balance };
    case "Deposited":
      return { balance: state.balance + event.amount };
    case "Withdrawn":
      return { balance: state.balance - event.amount };
  }
}, { balance: 0 });

결과:

accountProjection === { balance: 60 }

💡 왜 left-fold가 중요한가?


🧠 요약

개념 설명
left-fold 리스트를 왼쪽부터 차례로 처리해 누적 결과를 계산하는 함수형 연산 (reduce)
이벤트 소싱과의 연결 이벤트들을 left-fold해서 현재 상태를 계산하는 방식이 바로 프로젝션
프로젝션의 목적 이벤트 로그로부터 read model 또는 aggregate 상태를 복원